<template>
  <div class="daily_chart">
    <!--顶部条件-->
    <select-date ref="selectDate" @success="onSuccess" />
    <Tabs
      class="bg_white charts_tabs"
      v-model="TabVal"
      :animated="false"
      type="card"
      name="chartTab"
      @on-click="changeTabs">
      <TabPane
        :label="item.lable"
        :name="item.key"
        tab="chartTab"
        v-for="(item, index) in tabslist"
        v-if="item.flag"
        :key="index"></TabPane>
      <template #extra>
        <span class="change_statist_btn" @click="changeStatist()">切换统计项</span>
      </template>
    </Tabs>
    <div class="bg_white operation_item">
      <div class="charts_charts_status">
        <span>切换图表：</span>
        <RadioGroup v-model="chartsStatus" @on-change="changeEchart">
          <Radio label="optionBar">柱状图</Radio>
          <Radio label="optionLine">折线图</Radio>
          <Radio label="optionPie" v-if="chartsType != 4">饼图</Radio>
        </RadioGroup>
      </div>
      <div class="statistical_period">
        <span class="period">统计周期：{{ checkTime.startTime }}-{{ checkTime.endTime }}</span>
        <Button @click="changeStatisticalItem()" type="success">指标筛选</Button>
        <Button @click="downloadCharts" type="primary" style="margin: 0 10px">下载</Button>
      </div>
    </div>
    <div class="bg_white charts_warp">
      <chart-block ref="chart"></chart-block>
    </div>
    <change-statist-charts ref="changeStatistCharts" @success="onSuccess" />
    <filter-target-charts ref="filterTargetCharts" @success="onSuccess" />
    <dt-loading :loading="loading"></dt-loading>
  </div>
</template>

<script>
  import chartBlock from '@/components/echarts/eChartsBlock.vue'
  import chartsOption from '@/biz/buildingHome/charOption'
  import dailyChartsApi from '@/biz/buildingHome/dailyCharts'
  import dailyApi from '@/biz/buildingHome/daily'
  import selectDate from './component/echartsPage/component/selectDate.vue'
  import changeStatistCharts from './component/modal/changeStatistCharts.vue'
  import filterTargetCharts from './component/modal/filterTargetCharts.vue'
  export default {
    components: {
      chartBlock,
      changeStatistCharts,
      filterTargetCharts,
      selectDate
    },
    data() {
      return {
        checkTime: [], //日期
        chartsType: '', //统计项
        filterData: [], //指标筛选
        TabVal: '1',
        chartsStatus: 'optionBar',
        unit: '组',
        topText: '总成交',
        bottomText: '100',
        templateAllList: [],
        chartTabs: [
          {
            list: [
              { lable: 'PK数据（线索）', key: '1', flag: true },
              { lable: 'PK数据（来人）', key: '2', flag: true },
              { lable: 'PK数据（成交）', key: '3', flag: true }
            ]
          },
          {
            list: [
              { lable: '客户统计（线索）', key: '1', flag: true },
              { lable: '客户统计（来人）', key: '2', flag: true }
            ]
          },
          {},
          {
            list: [
              { lable: '销售统计（认购）', key: '1', flag: true },
              { lable: '销售统计（签约）', key: '2', flag: true }
            ]
          }
        ],
        tabslist: [],
        loading: false,
        pkDataFlagObj: null
      }
    },
    methods: {
      findDailyGenerationAllocationHomePage() {
        let params = {
          buildingId: this.$dt.buildInfo().housesId
        }
        dailyApi.findDailyGenerationAllocationHomePage(params).then((res) => {
          this.pkDataFlagObj = res
          if (this.pkDataFlagObj.clueStatus == 1) {
            this.TabVal = '1'
          } else if (this.pkDataFlagObj.arrivePeopleStatus == 1) {
            this.TabVal = '2'
          } else if (this.pkDataFlagObj.clinchDealStatus == 1) {
            this.TabVal = '3'
          }
          this.chartTabs[0].list[0].flag = this.pkDataFlagObj.clueStatus == 1 ? true : false
          this.chartTabs[0].list[1].flag = this.pkDataFlagObj.arrivePeopleStatus == 1 ? true : false
          this.chartTabs[0].list[2].flag = this.pkDataFlagObj.clinchDealStatus == 1 ? true : false
        })
      },
      //切换统计项
      changeStatist() {
        let data = {
          type: this.chartsType,
          templateAllList: this.templateAllList
        }
        this.$refs.changeStatistCharts.show(data)
      },
      //指标筛选
      changeStatisticalItem() {
        let data = {
          type: this.chartsType
        }
        this.$refs.filterTargetCharts.show(data)
      },
      //tabs切换
      changeTabs() {
        this.$refs.filterTargetCharts.getfilterListforTempalte({
          templateAllList: this.templateAllList,
          chartsType: this.chartsType,
          chartsStatus: this.chartsStatus,
          TabVal: this.TabVal
        })
        this.chartsStatus = 'optionBar'
        this.getinfoData(this.chartsStatus)
      },
      //切换表格形式
      changeEchart(type) {
        this.$refs.filterTargetCharts.getfilterListforTempalte({
          templateAllList: this.templateAllList,
          chartsType: this.chartsType,
          chartsStatus: this.chartsStatus,
          TabVal: this.TabVal
        })
        this.chartsStatus = type
        this.getinfoData(this.chartsStatus, true)
      },
      onSuccess(val) {
        //选择时间
        if (val.checkTime) {
          this.chartsStatus = 'optionBar'
          this.filterData = []
          this.checkTime = val.checkTime
        }
        //切换统计项
        if (val.type) {
          this.chartsStatus = 'optionBar'
          this.filterData = []
          this.chartsType = val.type
          this.tabslist = this.chartTabs[Number(this.chartsType) - 1]
            ? this.chartTabs[Number(this.chartsType) - 1].list
            : []
          if (this.chartsType == 3) {
            this.TabVal = this.tabslist.length ? this.tabslist[0].key : '1'
          } else {
            this.TabVal = '1'
          }
          this.$refs.filterTargetCharts.getfilterListforTempalte({
            templateAllList: this.templateAllList,
            chartsType: this.chartsType,
            chartsStatus: this.chartsStatus,
            TabVal: this.TabVal
          })
        }
        //筛选项
        if (val.filterData) {
          this.filterData = val.filterData
        }
        if (this.templateAllList.length) {
          this.getinfoData(this.chartsStatus)
        }
      },
      //获取数据 type: 需展示的图表 falg == true 时不需要调接口
      getinfoData(type, flag = false) {
        this.loading = true
        console.log(this.checkTime, '选择时间', this.chartsType, '切换统计项', this.filterData, '筛选项')
        let option = null
        //客户统计 线索统计 销售统计 根据模板配置展示图标\默认文字 pk数据根据数据返回是否有值判断
        let hasShow = false
        if (this.chartsType == 3 || this.chartsType == 4) {
          hasShow = this.templateAllList[Number(this.chartsType) - 1].hasShow
        } else if (this.chartsType == 2) {
          //客户统计 线索：1、来人：2    ***** TODO *****
          if (this.TabVal == 1) {
            hasShow = this.templateAllList[0].hasShow
          } else {
            hasShow = this.templateAllList[1].hasShow
          }
        } else {
          hasShow = true
        }
        if (!hasShow) {
          this.loading = false
          let text = dailyChartsApi.noDataTxt(this.chartsType)
          option = chartsOption.noData(text)
          this.$refs.chart.setOption(option)
        } else {
          let unit =
            this.chartsType == 4 ||
            (this.chartsType == 1 && this.TabVal == 3) ||
            (this.chartsType == 3 && (this.TabVal == 4 || this.TabVal == 5))
              ? '套'
              : '组'
          let params = {
            type,
            flag,
            checkTime: this.checkTime,
            chartsType: this.chartsType,
            filterData: this.$refs.filterTargetCharts.checkVals,
            TabVal: this.TabVal,
            unit: unit,
            topText: this.topText,
            bottomText: this.bottomText,
            templateAllList: this.templateAllList
          }
          dailyChartsApi
            .getInfoData(params)
            .then((res) => {
              this.loading = false
              if (this.chartsType == 1 && res.option.series.length == 0) {
                let text = dailyChartsApi.noDataTxt(1)
                option = chartsOption.noData(text)
                this.$refs.chart.setOption(option)
              } else {
                option = res.option
                //获取所有的指标筛选项 注：在chartsType==1 && chartsType==3（pk数据\渠道统计）时 取接口返回得数据作为筛选指标
                if (this.chartsType == 1 || this.chartsType == 3) {
                  this.$refs.filterTargetCharts.getfilterListforTempalte({
                    templateAllList: this.templateAllList,
                    chartsType: this.chartsType,
                    chartsStatus: this.chartsStatus,
                    TabVal: this.TabVal,
                    filterList: res.filterList
                  }) //获取客户统计 销售统计 指标筛选 list
                }
                this.$refs.chart.setOption(option)
              }
            })
            .catch(() => {
              this.loading = false
            })
        }
      },
      //获取案场日报模板
      getTemplate() {
        this.loading = true
        dailyApi.getModelList({ buildingId: this.$dt.buildInfo().housesId }).then((res) => {
          this.templateAllList = res
          this.$refs.filterTargetCharts.getfilterListforTempalte({
            templateAllList: this.templateAllList,
            chartsType: this.chartsType,
            chartsStatus: this.chartsStatus,
            TabVal: this.TabVal
          }) //获取客户统计 销售统计 指标筛选 list
          // 获取渠道统计tab list
          let data = res[2].childModelConfig.filter((item, index) => {
            item.lable = `渠道统计（${item.dailyConfigShortName}）`
            item.key = index + 1 + ''
            item.flag = true
            return item.hasLock
          })
          this.chartTabs[2].list = data
          this.tabslist = this.chartTabs[Number(this.chartsType) - 1]
            ? this.chartTabs[Number(this.chartsType) - 1].list
            : []
          if (this.chartsType == 3) {
            this.TabVal = this.tabslist.length ? this.tabslist[0].key : '1'
          }
          if (this.templateAllList) {
            this.getinfoData(this.chartsStatus)
          }
        })
      },
      //下载charts 将图形转成base64的图片
      downloadCharts() {
        let canvas = this.$refs.chart.$el.getElementsByTagName('canvas')[0]
        dailyChartsApi.chartsToBase64(canvas, '#fff').then((res) => {
          dailyChartsApi.downloadBase64(res, '日报')
        })
      }
    },
    mounted() {
      this.chartsType = this.$route.query.type
      this.getTemplate()
      this.findDailyGenerationAllocationHomePage()
      this.$refs.selectDate.topChooseClick(0)
    }
  }
</script>
<style lang="scss" scoped>
  .daily_chart {
    padding: 20px;
    background-color: #f5f7f9;

    .charts_tabs {
      padding: 10px 20px 0 20px;

      .change_statist_btn {
        color: #0088ff;
        cursor: pointer;
      }
    }

    .operation_item {
      padding: 10px 20px 20px 20px;

      .charts_charts_status {
        padding-bottom: 10px;
        border-radius: 5px;
      }

      .statistical_period {
        font-size: 16px;
        color: #8f8f8f;

        .period {
          margin-right: 20px;
          line-height: 32px;
        }
      }
    }

    .charts_warp {
      height: calc(100vh - 350px);
      overflow: hidden;
    }

    .bg_white {
      background: #fff;
    }
  }
</style>
